package xin.shaozeming.base.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import xin.shaozeming.base.common.ex.CustomerException;
import xin.shaozeming.base.common.ex.NetRunException;
import xin.shaozeming.base.common.utils.DateUtils;
import xin.shaozeming.base.common.utils.ObjConverter;
import xin.shaozeming.base.common.utils.ParamUtils;
import xin.shaozeming.base.common.utils.RandomCode;
import xin.shaozeming.base.po.RolePermissionPO;
import xin.shaozeming.base.po.UserPO;
import xin.shaozeming.base.dao.UserDao;
import xin.shaozeming.base.po.UserRolePO;
import xin.shaozeming.base.service.UserRoleService;
import xin.shaozeming.base.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xin.shaozeming.base.vo.UserVO;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 邵泽铭
 * @since 2019-08-22
 */
@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserPO> implements UserService {
    @Resource
    private UserDao userDao;

    @Resource
    private UserRoleService userRoleService;
    /**
     * 检测token是否失效
     *
     * @param token
     * @return
     */
    @Override
    public UserPO checkToken(String token) {
        QueryWrapper<UserPO> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        wrapper.last(" limit 1");
        UserPO userPO = userDao.selectOne(wrapper);
        if (userPO == null) {
            return null;
        } else {
            if (userPO.getTokenExpire() == null) {
                return null;
            }
            if (DateUtil.isExpired(new Date(), DateField.SECOND, 0, userPO.getTokenExpire())) {
                return null;
            } else {
                return userPO;
            }
        }
    }

    @Override
    public UserVO login(String userName, String password) {

        UserPO userPO = lambdaQuery().eq(UserPO::getUsername,userName )
                .eq(UserPO::getState,0 ).one();
        if (userPO == null) {
            throw  new CustomerException("用户名不存在");
        }
        if(!userPO.getPassword().equals(password)){
            throw  new CustomerException("密码不正确");
        }

        String token = RandomCode.createToken();
        userPO.setToken(token);
        userPO.setTokenExpire(DateUtils.addDate(new Date(), 20));
        userPO.setLastLoginTime(new Date());
        int count = userDao.updateById(userPO);
        if (count < 1) {
            throw new NetRunException();
        }
        return ObjConverter.convert(userPO, UserVO.class);
    }

    /**
     * 修改密码
     *
     * @param token
     * @param newPassword
     * @param oldPassword
     * @return
     */
    @Override
    public boolean updatePassword(String token, String newPassword, String oldPassword) {
        UserPO userPO = checkToken(token);
        if(userPO==null){
            throw  new CustomerException("当前账号状态无法修改密码");
        }
        if(!userPO.getPassword().equals(oldPassword)){
            throw  new CustomerException("密码错误");
        }
        userPO.setPassword(newPassword);
        return saveOrUpdate(userPO);
    }

    /**
     * 保存用户
     *
     * @param userPO
     * @param roleIds
     * @return
     */
    @Override
    public boolean saveUser(UserPO userPO, String roleIds) {

        ParamUtils.parseDecideSaveOrUpdate(UserPO.class, userPO);

        if(!saveOrUpdate(userPO)){
            throw  new CustomerException("保存用户失败");
        }
        if(!StringUtils.isEmpty(roleIds)){
            List<UserRolePO> list=new ArrayList<>();
            String[] array= roleIds.split(",");
            for (int i=0;i<array.length;i++){
                UserRolePO userRolePO=new UserRolePO();
                Integer roleId=  new Integer(array[i]);
                userRolePO.setRoleId(roleId);
                userRolePO.setUserId(userPO.getId());
                list.add(userRolePO);
            }
            if(list.size()>0){
                if(!userRoleService.updateUserRoleByRole(userPO.getId(),list)){
                    throw  new CustomerException("保存用户失败");
                }
            }
        }


        return true;
    }
}
